<template>
  <el-dialog title="导入学员" :visible="visible" width="400px" top="30vh" :before-close="handleClose" :close-on-click-modal="false">
    <el-form ref="student" :model="user" size="small">
      <el-form-item prop="attach_id" label="请上传附件" :rules="rulesFile">
        <edu-upload :value.sync="user.attach_id" field="attach_id" :args="uploadArgs" />
      </el-form-item>
      <el-form-item>
        <el-row type="flex" justify="end">
          <el-button type="primary" :disabled="disableSubmit" @click="onSubmit">保存</el-button>
          <el-button @click="$emit('update:visible', false)">取消</el-button>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import EduUpload from '@public/form/upload';
export default {
  components: {
    EduUpload
  },
  props: {
    courseId: {
      type: [Number, String],
      required: true
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  inject: ['reload'],
  data() {
    return {
      user: {
        attach_id: ''
      },
      rulesFile: [{ required: true, message: '请上传附件', trigger: ['blur', 'change'] }],
      disableSubmit: false,
      uploadArgs: {
        limit: 1,
        accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
        autoupload: 1,
        upload_params: {
          is_temp: true
        }
      }
    };
  },
  methods: {
    handleClose() {
      this.$emit('update:visible', false);
    },
    onSubmit: function() {
      this.$refs['student'].validate(valid => {
        if (valid) {
          this.disableSubmit = true;
          this.$http.post(
            '/course/admin/' + this.courseId + '/student/import',
            {
              attach_id: this.user.attach_id
            },
            response => {
              const data = response.data;
              this.$box
                .success('共计' + data.total + '个学员，成功导入' + data.success + '个，其中' + data.exists + '个学员已在该课程中', {
                  duration: 0
                })
                .then(() => {
                  this.reload();
                })
                .catch(() => {});
            },
            error => {
              this.$box.error(error.msg, {
                duration: 0
              });
              this.disableSubmit = false;
            },
            false
          );
        }
      });
    }
  }
};
</script>

<style></style>
